import os
import sys
import time
import random
import json
import sqlite3
import datetime
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 导入应用
from app import create_app
from models import Device, DeviceData
from database import db

# 创建应用实例
app = create_app()

# 设备ID列表
DEVICE_IDS = [
    "TW001", "TW002", "TW003", "TW004", "TW005",
    "TW006", "TW007", "TW008", "TW009", "TW010"
]

# 设备名称列表
DEVICE_NAMES = [
    "换位机A1", "换位机A2", "换位机B1", "换位机B2", "换位机C1",
    "换位机C2", "换位机D1", "换位机D2", "换位机E1", "换位机E2"
]

# 设备类型列表
DEVICE_TYPES = [
    "CTC换位机", "CTC换位机", "CTC换位机", "CTC换位机", "CTC换位机",
    "CTC换位机", "CTC换位机", "CTC换位机", "CTC换位机", "CTC换位机"
]

# 设备位置列表
DEVICE_LOCATIONS = [
    "A区1号", "A区2号", "B区1号", "B区2号", "C区1号",
    "C区2号", "D区1号", "D区2号", "E区1号", "E区2号"
]

# 设备状态列表
DEVICE_STATUSES = ["online", "offline", "error"]

# 生成随机设备数据
def generate_device_data(device_id, timestamp=None):
    # 随机生成设备状态，大部分时间为在线状态
    status = random.choices(
        DEVICE_STATUSES, 
        weights=[0.8, 0.15, 0.05], 
        k=1
    )[0]
    
    # 根据状态生成不同的数据
    if status == "online":
        # 在线状态，生成正常的生产数据
        production_speed = random.uniform(10.0, 30.0)  # 10-30米/分钟
        production_length = random.uniform(1000.0, 5000.0)  # 1000-5000米
        temperature = random.uniform(20.0, 35.0)  # 20-35摄氏度
        humidity = random.uniform(40.0, 70.0)  # 40%-70%
        pressure = random.uniform(95.0, 105.0)  # 95-105kPa
        error_code = ""
    elif status == "offline":
        # 离线状态，生产数据为0
        production_speed = 0
        production_length = random.uniform(1000.0, 5000.0)  # 保留之前的生产长度
        temperature = 0
        humidity = 0
        pressure = 0
        error_code = ""
    else:  # error
        # 错误状态，生成异常数据
        production_speed = random.uniform(0.0, 5.0)  # 0-5米/分钟
        production_length = random.uniform(1000.0, 5000.0)  # 保留之前的生产长度
        temperature = random.uniform(35.0, 45.0)  # 35-45摄氏度（过高）
        humidity = random.uniform(20.0, 90.0)  # 20%-90%（异常范围）
        pressure = random.uniform(90.0, 110.0)  # 90-110kPa（异常范围）
        error_codes = ["E001", "E002", "E003", "E004", "E005"]
        error_code = random.choice(error_codes)
    
    # 如果没有提供时间戳，使用当前时间
    if timestamp is None:
        timestamp = datetime.datetime.utcnow()
    
    # 返回设备数据
    return {
        "device_id": device_id,
        "status": status,
        "production_speed": round(production_speed, 2),
        "production_length": round(production_length, 2),
        "temperature": round(temperature, 1),
        "humidity": round(humidity, 1),
        "pressure": round(pressure, 1),
        "error_code": error_code,
        "timestamp": timestamp.isoformat()
    }

# 生成历史数据
def generate_historical_data(days=1):
    with app.app_context():
        # 确保设备存在
        for i in range(len(DEVICE_IDS)):
            device = Device.query.filter_by(device_id=DEVICE_IDS[i]).first()
            if not device:
                device = Device(
                    device_id=DEVICE_IDS[i],
                    name=DEVICE_NAMES[i],
                    type=DEVICE_TYPES[i],
                    location=DEVICE_LOCATIONS[i],
                    status="offline"
                )
                db.session.add(device)
        
        db.session.commit()
        
        # 生成历史数据
        now = datetime.datetime.utcnow()
        start_time = now - datetime.timedelta(days=days)
        
        # 每10分钟一条数据
        interval = datetime.timedelta(minutes=10)
        current_time = start_time
        
        while current_time < now:
            for i, device_id in enumerate(DEVICE_IDS):
                device = Device.query.filter_by(device_id=device_id).first()
                
                # 生成设备数据
                data = generate_device_data(device_id, current_time)
                
                # 更新设备状态
                device.status = data["status"]
                device.last_update = current_time
                
                # 创建设备数据记录
                device_data = DeviceData(
                    device_id=device.id,
                    timestamp=current_time,
                    production_speed=data["production_speed"],
                    production_length=data["production_length"],
                    temperature=data["temperature"],
                    humidity=data["humidity"],
                    pressure=data["pressure"],
                    error_code=data["error_code"]
                )
                
                db.session.add(device_data)
            
            # 提交事务
            db.session.commit()
            
            # 更新时间
            current_time += interval
            
            # 打印进度
            progress = (current_time - start_time) / (now - start_time) * 100
            print(f"生成历史数据: {progress:.2f}% 完成", end="\r")
        
        print("\n历史数据生成完成!")

# 实时生成数据
def generate_realtime_data(interval=60):
    with app.app_context():
        print("开始生成实时数据，按Ctrl+C停止...")
        
        try:
            while True:
                for i, device_id in enumerate(DEVICE_IDS):
                    device = Device.query.filter_by(device_id=device_id).first()
                    if not device:
                        continue
                    
                    # 生成设备数据
                    data = generate_device_data(device_id)
                    
                    # 更新设备状态
                    device.status = data["status"]
                    device.last_update = datetime.datetime.utcnow()
                    
                    # 创建设备数据记录
                    device_data = DeviceData(
                        device_id=device.id,
                        timestamp=datetime.datetime.utcnow(),
                        production_speed=data["production_speed"],
                        production_length=data["production_length"],
                        temperature=data["temperature"],
                        humidity=data["humidity"],
                        pressure=data["pressure"],
                        error_code=data["error_code"]
                    )
                    
                    db.session.add(device_data)
                
                # 提交事务
                db.session.commit()
                
                print(f"数据已生成: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
                
                # 等待下一次生成
                time.sleep(interval)
        
        except KeyboardInterrupt:
            print("\n停止生成实时数据")

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="生成模拟数据")
    parser.add_argument("--historical", action="store_true", help="生成历史数据")
    parser.add_argument("--days", type=int, default=1, help="生成多少天的历史数据")
    parser.add_argument("--realtime", action="store_true", help="生成实时数据")
    parser.add_argument("--interval", type=int, default=60, help="实时数据生成间隔（秒）")
    
    args = parser.parse_args()
    
    if args.historical:
        generate_historical_data(args.days)
    
    if args.realtime:
        generate_realtime_data(args.interval)
    
    if not args.historical and not args.realtime:
        print("请指定至少一个操作: --historical 或 --realtime")
        parser.print_help()
